package com.ecp.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.log4j.Logger;

/**
 * 序列号生成
 * @author zhanghao
 *
 */
public class SerialNumberUtil {
	private static Logger		logger				= Logger.getLogger(SerialNumberUtil.class);

	public static final String	PRODUCT_SN_PREFIX	= "SN_";
	public static final String  PVTRANSACTION_SN_PREFIX = "PVT_";
	public static final String  JKTRANSACTION_SN_PREFIX = "JK_";

	public static String buildProductSn() {
		String uuid = UUID.randomUUID().toString();
		return PRODUCT_SN_PREFIX + (uuid.substring(0, 8) + uuid.substring(9, 13)).toUpperCase();
	}
	
	public static String buildPVTransactionSn() {
		String uuid = UUID.randomUUID().toString();
		return PVTRANSACTION_SN_PREFIX + (uuid.substring(0, 8) + uuid.substring(9, 13)).toUpperCase();
	}
	
	public static String buildJKTransactionSn() {
		String uuid = UUID.randomUUID().toString();
		return JKTRANSACTION_SN_PREFIX + (uuid.substring(0, 8) + uuid.substring(9, 13)).toUpperCase();
	}

	/**
	 * 购物车序列号生成器
	 * 服务器名称 + '-' + 系统时间
	 * @return
	 */
	public static String buildShoppingCartSerialNumber() {
		InetAddress addr = null;
		StringBuffer serialNumber = new StringBuffer();
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			logger.error("get InetAddress error");
			throw new RuntimeException(e);
		}
		if (addr == null) {
			return null;
		}
		String hostName = addr.getHostName().toString(); //获取本机计算机名称 
		Long currentTimeMillis = System.currentTimeMillis();//获取当前系统时间
		serialNumber.append(hostName).append("-").append(currentTimeMillis);
		return serialNumber.toString();
	}
	
	public static String buildPackageCartItemSerialNumber(Set<Integer> iObjectIdSet){
		StringBuilder snBuilder = new StringBuilder("PCI_");
		List<Integer> list = new ArrayList<Integer>();
		for (Integer i : iObjectIdSet) {
			list.add(i);
		}
		java.util.Collections.sort(list);
		for (Integer i2 : list) {
			snBuilder.append(i2);
		}
		return snBuilder.toString();
	}

	/**
	 * 购物项序列号生成器
	 * 服务器名称 + '-' + 商品编号
	 * 如果是订单赠品商品编号 + _1
	 * @return
	 */
	public static String buildShoppingCartItemSerialNumber(String productId) {
		InetAddress addr = null;
		StringBuffer serialNumber = new StringBuffer();
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			logger.error("get InetAddress error");
			throw new RuntimeException(e);
		}
		if (addr == null) {
			return null;
		}
		String hostName = addr.getHostName().toString(); //获取本机计算机名称 
		serialNumber.append(hostName).append("-").append(productId);
		return serialNumber.toString();
	}
}
